﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace HttpClientStudy.Config
{
    public static class WebApiConfigManager
    {
        public static WebApiConfig GetWebApiConfig()
        { 
            return GetWebApiConfigOption().CurrentValue; 
        }

        public static IOptionsMonitor<WebApiConfig> GetWebApiConfigOption()
        {
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.AddWebApiConfiguration();

            ServiceCollection services = new ServiceCollection();
            services.AddSingleton<IConfiguration>(configurationBuilder.Build());
            services.UseWebApiOptions();

            var webApiConfigOption = services.BuildServiceProvider().GetService<IOptionsMonitor<WebApiConfig>>();
            if (webApiConfigOption == null)
            {
                throw new OptionsValidationException(nameof(webApiConfigOption), typeof(IOptions<WebApiConfig>), new[] { "获取配置异常"});
            }

            return webApiConfigOption;
        }
    }
}
